#include <windows.h>

#include "monitors.h"
#include "window.h"
#include "mmbar.h"
#include "support.h"
#include "system.h"
#include "taskbar.h"
#include "events.h"
#include "config.h"

#define MutexName "MonMan {73fe1693-6410-4095-b46b-b61a1f260b9f}"

HANDLE mutex;

static void cleanup(void);

int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR arg, int show)
{
	HANDLE mutex = CreateMutex(0, FALSE, MutexName);
	if(GetLastError() == ERROR_ALREADY_EXISTS)
	{
		MessageBox(0, "MonMan is already running", "MonMan", MB_ICONINFORMATION);
		return 0;
	}
	
#ifdef DEBUG
	init_debug();
#endif

	init_taskbar();
	init_windows();
	init_mmbar();
	init_monitors();
	
	track_windows();
#if Cfg_UseHooks
	install_hooks();
#endif
#if Cfg_UseEvents
	install_event_handlers();
#endif
	install_crash_handler(cleanup);
	process_messages();
	
	cleanup();
	
	return EXIT_SUCCESS;
}

static void cleanup(void)
{
#if Cfg_UseEvents
	free_event_handlers();
#endif
#if Cfg_UseHooks
	free_hooks();
#endif
	free_monitors();
	free_windows();
	free_taskbar();
	
	CloseHandle(mutex);
}

